import axios from 'axios';
import warning from 'warning';
import createError from './createError';

// mock url
const url = 'https://easy-mock.com/mock/5b4effb19c3913354f3ae523';

export function request(path, body = {}) {
  return (
    axios
      .post(`${url}${path}`, JSON.stringify(body))
      .then(response => response.data)
      // .then(response => {
      //   if (response.status === 1) {
      //     throw createError(response.code);
      //   }
      //   // return JSON.parse(response.body || '{}');
      //   return response.body || '{}';
      // })
      .catch(error => {
        if (error instanceof SyntaxError) {
          warning(false, 'JSON 解析错误');
          throw createError('SYNTAX_JSON');
        }

        // 超时
        if (error.code === 'ECONNABORTED') {
          warning(false, '网络请求超时');
          throw createError('ECONNABORTED');
        }

        if (error.code !== undefined) {
          throw error;
        }

        warning(false, '未知错误');
        throw createError('ERROR');
      })
  );
}
